define([], function () {
    require(['../addons/bootstrapcontextmenu/js/bootstrap-contextmenu'], function (undefined) {
    if (Config.controllername == 'index' && Config.actionname == 'index') {
        $("body").append(
            '<div id="context-menu">' +
            '<ul class="dropdown-menu" role="menu">' +
            '<li><a tabindex="-1" data-operate="refresh"><i class="fa fa-refresh fa-fw"></i>刷新</a></li>' +
            '<li><a tabindex="-1" data-operate="refreshTable"><i class="fa fa-table fa-fw"></i>刷新表格</a></li>' +
            '<li><a tabindex="-1" data-operate="close"><i class="fa fa-close fa-fw"></i>关闭</a></li>' +
            '<li><a tabindex="-1" data-operate="closeOther"><i class="fa fa-window-close-o fa-fw"></i>关闭其他</a></li>' +
            '<li class="divider"></li>' +
            '<li><a tabindex="-1" data-operate="closeAll"><i class="fa fa-power-off fa-fw"></i>关闭全部</a></li>' +
            '</ul>' +
            '</div>');

        $(".nav-addtabs").contextmenu({
            target: "#context-menu",
            scopes: 'li[role=presentation]',
            onItem: function (e, event) {
                var $element = $(event.target);
                var tab_id = e.attr('id');
                var id = tab_id.substr('tab_'.length);
                var con_id = 'con_' + id;
                switch ($element.data('operate')) {
                    case 'refresh':
                        $("#" + con_id + " iframe").attr('src', function (i, val) {
                            return val;
                        });
                        break;
                    case 'refreshTable':
                        try {
                            if ($("#" + con_id + " iframe").contents().find(".btn-refresh").size() > 0) {
                                $("#" + con_id + " iframe")[0].contentWindow.$(".btn-refresh").trigger("click");
                            }
                        } catch (e) {

                        }
                        break;
                    case 'close':
                        if (e.find(".close-tab").length > 0) {
                            e.find(".close-tab").click();
                        }
                        break;
                    case 'closeOther':
                        e.parent().find("li[role='presentation']").each(function () {
                            if ($(this).attr('id') == tab_id) {
                                return;
                            }
                            if ($(this).find(".close-tab").length > 0) {
                                $(this).find(".close-tab").click();
                            }
                        });
                        break;
                    case 'closeAll':
                        e.parent().find("li[role='presentation']").each(function () {
                            if ($(this).find(".close-tab").length > 0) {
                                $(this).find(".close-tab").click();
                            }
                        });
                        break;
                    default:
                        break;
                }
            }
        });
    }
    $(document).on('click', function () { // iframe内点击 隐藏菜单
        try {
            top.window.$(".nav-addtabs").contextmenu("closemenu");
        } catch (e) {
        }
    });

});
//判断系统深色模式变化，修改切换按钮
var matchMedia = window.matchMedia(('(prefers-color-scheme: dark)'));
matchMedia.addEventListener('change', function () {
    var mode = this.matches ? 'dark' : 'light';
    //只有当cookie中无手动定义值时才进行操作
    if (document.cookie.indexOf("thememode=") === -1 && Config.darktheme.mode === 'auto') {
        $("body").toggleClass("darktheme", mode === "dark");
    }
});

if (typeof Config.darktheme !== 'undefined' && Config.darktheme.switchbtn) {

    // 切换模式
    var switchMode = function (mode) {
        // 获取当前深色模式
        if (mode === 'auto') {
            var isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches;
            mode = isDarkMode ? 'dark' : 'light';
        }

        if (mode === 'auto') {
        } else if (mode === 'dark') {
            $("body").addClass("darktheme");
            $(".darktheme-link").removeAttr("media");
        } else {
            $("body").removeClass("darktheme");
            $(".darktheme-link").attr("media", "(prefers-color-scheme: dark)");
        }
    };

    // 创建Cookie
    var createCookie = function (name, value) {
        var date = new Date();
        date.setTime(date.getTime() + (365 * 24 * 60 * 60 * 1000));
        var url = Config.moduleurl.replace(location.origin, "");
        var path = url ? url.substring(url.lastIndexOf("/")) : "/";
        document.cookie = encodeURIComponent(Config.cookie.prefix + name) + "=" + encodeURIComponent(value) + "; path=" + path + "; expires=" + date.toGMTString();
    };

    if (Config.controllername === 'index' && Config.actionname === 'index') {
        var mode = Config.darktheme.mode;
        if (mode === 'auto') {
            var isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches;
            mode = isDarkMode ? 'dark' : 'light';
        }
        var html = '<li class="theme-li">' +
            '<button type="button" title="切换' + (mode === 'dark' ? '浅色' : '深色') + '模式" data-mode="' + (mode === 'dark' ? 'light' : 'dark') + '" class="theme-toggle">' +
            '<svg class="sun-and-moon" aria-hidden="true" width="24" height="24" viewBox="0 0 24 24">\n' +
            '      <circle class="sun" cx="12" cy="12" r="6" mask="url(#moon-mask)" fill="currentColor" />\n' +
            '      <g class="sun-beams" stroke="currentColor">\n' +
            '        <line x1="12" y1="1" x2="12" y2="3" />\n' +
            '        <line x1="12" y1="21" x2="12" y2="23" />\n' +
            '        <line x1="4.22" y1="4.22" x2="5.64" y2="5.64" />\n' +
            '        <line x1="18.36" y1="18.36" x2="19.78" y2="19.78" />\n' +
            '        <line x1="1" y1="12" x2="3" y2="12" />\n' +
            '        <line x1="21" y1="12" x2="23" y2="12" />\n' +
            '        <line x1="4.22" y1="19.78" x2="5.64" y2="18.36" />\n' +
            '        <line x1="18.36" y1="5.64" x2="19.78" y2="4.22" />\n' +
            '      </g>\n' +
            '      <mask class="moon" id="moon-mask">\n' +
            '        <rect x="0" y="0" width="100%" height="100%" fill="white" />\n' +
            '        <circle cx="24" cy="10" r="6" fill="black" />\n' +
            '      </mask>\n' +
            '    </svg>' +
            '</button>' +
            '</li>';
        $(html).prependTo("#firstnav > div > ul");

        //点击切换按钮
        $(document).on("click", ".theme-toggle", function () {
            var mode = $(this).attr("data-mode");
            switchMode(mode);
            createCookie("thememode", mode);
            $("iframe").each(function () {
                try {
                    $(this)[0].contentWindow.$("body").trigger("swithmode", [mode]);
                } catch (e) {

                }
            });
            $(this).attr("data-mode", mode === 'dark' ? 'light' : 'dark').attr("title", '切换' + (mode === 'dark' ? '浅色' : '深色') + '模式');
        });

        //判断系统深色模式变化，修改切换按钮
        var matchMedia = window.matchMedia(('(prefers-color-scheme: dark)'));
        matchMedia.addEventListener('change', function () {
            var mode = this.matches ? 'dark' : 'light';
            //只有当cookie中无手动定义值时才切换
            if (document.cookie.indexOf("thememode=") === -1 && Config.darktheme.mode === 'auto') {
                $(".theme-toggle").attr("data-mode", mode === 'dark' ? 'light' : 'dark').attr("title", '切换' + (mode === 'dark' ? '浅色' : '深色') + '模式');
            }
        });
    } else {
        //添加事件
        $("body").on("swithmode", function (e, mode) {
            switchMode(mode);
            $("iframe").each(function () {
                try {
                    $(this)[0].contentWindow.$("body").trigger("swithmode", [mode]);
                } catch (e) {

                }
            });
        });
    }
}
require.config({
    paths: {
        'bootstrap-markdown': '../addons/markdown/js/bootstrap-markdown.min',
        'hyperdown': '../addons/markdown/js/hyperdown.min',
        'turndown': '../addons/markdown/js/turndown',
        'jquery-autocomplete': '../addons/cms/js/jquery.autocomplete',
        'jquery-tagsinput': '../addons/cms/js/jquery.tagsinput',
    },
    shim: {
        'bootstrap-markdown': {
            deps: [
                'jquery',
                'css!../addons/markdown/css/bootstrap-markdown.css'
            ],
            exports: '$.fn.markdown'
        },
        'jquery-autocomplete': {
            deps: ['jquery'],
            exports: '$.fn.extend'
        },
        'jquery-tagsinput': {
            deps: ['jquery', 'jquery-autocomplete', 'css!../addons/cms/css/jquery.tagsinput.min.css'],
            exports: '$.fn.extend'
        }
    }
});
require(['form', 'upload'], function (Form, Upload) {
    var _bindevent = Form.events.bindevent;
    Form.events.bindevent = function (form) {
        _bindevent.apply(this, [form]);
        var insert = function (e, url, type) {
            var urlArr = url.split(/\,/);
            $.each(urlArr, function () {
                var url = Fast.api.cdnurl(this, true);
                if (type && type == 'image') {
                    e.replaceSelection("\n" + '![输入图片说明](' + url + ')');
                } else {
                    e.replaceSelection("\n" + '[输入链接说明](' + url + ')');
                }
            });
            e.change(e);
            // e.$element.blur();
            // e.$element.focus();
        };
        try {
            if ($(Config.markdown.classname || '.editor', form).length > 0) {
                require(['bootstrap-markdown', 'hyperdown', 'turndown'], function (undefined, undefined, Turndown) {
                    $.fn.markdown.messages.zh = {
                        Bold: "粗体",
                        Italic: "斜体",
                        Heading: "标题",
                        "URL/Link": "链接",
                        Image: "图片",
                        List: "列表",
                        "Unordered List": "无序列表",
                        "Ordered List": "有序列表",
                        Code: "代码",
                        Quote: "引用",
                        Preview: "预览",
                        "strong text": "粗体",
                        "emphasized text": "强调",
                        "heading text": "标题",
                        "enter link description here": "输入链接说明",
                        "Insert Hyperlink": "URL地址",
                        "enter image description here": "输入图片说明",
                        "Insert Image Hyperlink": "图片URL地址",
                        "enter image title here": "在这里输入图片标题",
                        "list text here": "这里是列表文本",
                        "code text here": "这里输入代码",
                        "quote here": "这里输入引用文本"
                    };
                    var parser = new HyperDown();
                    window.marked = function (text) {
                        return parser.makeHtml(text);
                    };
                    var uploadFiles;
                    uploadFiles = async function (files) {
                        var self = this;
                        for (var i = 0; i < files.length; i++) {
                            try {
                                await new Promise((resolve) => {
                                    var url, html, file;
                                    file = files[i];
                                    Upload.api.send(file, function (data) {
                                        url = Fast.api.cdnurl(data.url, true);
                                        if (file.type.indexOf("image") !== -1) {
                                            insert(self, url, 'image');
                                        } else {
                                            insert(self, url, 'file');
                                        }
                                        resolve();
                                    }, function () {
                                        resolve();
                                    });
                                });
                            } catch (e) {

                            }
                        }
                    };

                    $(Config.markdown.classname || '.editor', form).each(function () {
                        var options = $(this).data("markdown-options") || {};
                        var editor = $(this);
                        var format = typeof options.format !== 'undefined' ? options.format : Config.markdown.format;
                        if (format === 'html') {
                            var origin = editor;
                            var turndownService = new TurndownService();
                            turndownService.use(turndownPluginGfm.gfm);
                            var content = turndownService.turndown(origin.val());

                            editor = origin.clone().removeAttr("name").removeAttr("id").val(content);
                            origin.css("display", "none");
                            editor.data("markdown-origin", origin);
                            editor.insertAfter(origin);
                        }
                        (function (editor) {
                            editor.markdown($.extend(true, {
                                resize: 'vertical',
                                language: 'zh',
                                iconlibrary: 'fa',
                                autofocus: false,
                                savable: false,
                                additionalButtons: [
                                    [{
                                        name: "groupCustom",
                                        data: [{
                                            name: "cmdUploadImage",
                                            toggle: false,
                                            title: "Upload image",
                                            icon: "fa fa-upload",
                                        }, {
                                            name: "cmdUploadFile",
                                            toggle: false,
                                            title: "Upload file",
                                            icon: "fa fa-cloud-upload",
                                        }, {
                                            name: "cmdSelectImage",
                                            toggle: false,
                                            title: "Select image",
                                            icon: "fa fa-file-image-o",
                                            callback: function (e) {
                                                parent.Fast.api.open("general/attachment/select?element_id=&multiple=true&mimetype=image/*", __('Choose'), {
                                                    callback: function (data) {
                                                        var urlArr = data.url.split(/\,/);
                                                        insert(e, data.url, 'image');
                                                    }
                                                });
                                                return false;
                                            }
                                        }, {
                                            name: "cmdSelectAttachment",
                                            toggle: false,
                                            title: "Select file",
                                            icon: "fa fa-file",
                                            callback: function (e) {
                                                parent.Fast.api.open("general/attachment/select?element_id=&multiple=true&mimetype=*", __('Choose'), {
                                                    callback: function (data) {
                                                        insert(e, data.url, 'file');
                                                    }
                                                });
                                                return false;
                                            }
                                        }]
                                    }]
                                ],
                                onShow: function (e) {
                                    //添加上传图片按钮和上传附件按钮
                                    var imgBtn = $("button[data-handler='bootstrap-markdown-cmdUploadImage']", e.$editor);
                                    var fileBtn = $("button[data-handler='bootstrap-markdown-cmdUploadFile']", e.$editor);
                                    var btnParent = imgBtn.parent();
                                    btnParent.addClass("md-relative");

                                    var upImgBtn = $('<button type="button" class="uploadimage faupload" data-button="image" title="点击上传图片" data-mimetype="image/gif,image/jpeg,image/png,image/jpg,image/bmp,image/webp" data-multiple="true">点击上传图片</button>');
                                    upImgBtn.css(imgBtn.position()).appendTo(btnParent);

                                    var upFileBtn = $('<button type="button" class="uploadfile faupload" data-button="file" title="点击上传附件" data-multiple="true">点击上传附件</button>');
                                    upFileBtn.css(fileBtn.position()).appendTo(btnParent);

                                    upImgBtn.data("upload-success", function (data, ret) {
                                        insert(e, data.url, 'image');
                                    });
                                    upFileBtn.data("upload-success", function (data, ret) {
                                        insert(e, data.url, 'file');
                                    });
                                    Form.events.faupload(e.$editor);

                                    $(".uploadimage,.uploadfile", e.$editor).on("mouseenter", function () {
                                        ($(this).data("button") === 'image' ? imgBtn : fileBtn).addClass("active");
                                    }).on("mouseleave", function () {
                                        ($(this).data("button") === 'image' ? imgBtn : fileBtn).removeClass("active");
                                    });

                                    //粘贴上传
                                    $(e.$textarea).bind('paste', function (event) {
                                        var originalEvent;
                                        originalEvent = event.originalEvent;
                                        if (originalEvent.clipboardData && originalEvent.clipboardData.files.length > 0) {
                                            uploadFiles.call(e, originalEvent.clipboardData.files);
                                            return false;
                                        }
                                    });
                                    //拖拽上传
                                    $(e.$textarea).bind('drop', function (event) {
                                        var originalEvent;
                                        originalEvent = event.originalEvent;
                                        if (originalEvent.dataTransfer && originalEvent.dataTransfer.files.length > 0) {
                                            uploadFiles.call(e, originalEvent.dataTransfer.files);
                                            return false;
                                        }
                                    });
                                },
                                onChange: function (e) {
                                    var origin = $(e.$textarea).data("markdown-origin");
                                    if (origin) {
                                        origin.val(marked(e.$textarea.val()));
                                    }
                                }
                            }, editor.data("markdown-options") || {}));
                        })(editor)
                    });
                });
            }
        } catch (e) {
            console.log(e);
        }

    };
});

require.config({
    paths: {
        'nkeditor': '../addons/nkeditor/js/customplugin',
        'nkeditor-core': '../addons/nkeditor/nkeditor',
        'nkeditor-lang': '../addons/nkeditor/lang/zh-CN',
    },
    shim: {
        'nkeditor': {
            deps: [
                'nkeditor-core',
                'nkeditor-lang'
            ]
        },
        'nkeditor-core': {
            deps: [
                'css!../addons/nkeditor/themes/black/editor.min.css',
                'css!../addons/nkeditor/css/common.css'
            ],
            exports: 'window.KindEditor'
        },
        'nkeditor-lang': {
            deps: [
                'nkeditor-core'
            ]
        }
    }
});
require(['form'], function (Form) {
    var _bindevent = Form.events.bindevent;
    Form.events.bindevent = function (form) {
        _bindevent.apply(this, [form]);
        if ($(Config.nkeditor.classname || '.editor', form).length > 0) {
            require(['nkeditor', 'upload'], function (Nkeditor, Upload) {
                var getFileFromBase64, uploadFiles;
                uploadFiles = async function (files) {
                    var self = this;
                    for (var i = 0; i < files.length; i++) {
                        try {
                            await new Promise((resolve) => {
                                var url, html, file;
                                file = files[i];
                                Upload.api.send(file, function (data) {
                                    url = Config.nkeditor.fullmode ? Fast.api.cdnurl(data.url, true) : Fast.api.cdnurl(data.url);
                                    if (file.type.indexOf("image") !== -1) {
                                        self.exec("insertimage", url);
                                    } else {
                                        html = '<a class="ke-insertfile" href="' + url + '" data-ke-src="' + url + '" target="_blank">' + (file.name || url) + '</a>';
                                        self.exec("inserthtml", html);
                                    }
                                    resolve();
                                }, function () {
                                    resolve();
                                });
                            });
                        } catch (e) {

                        }
                    }
                };
                getFileFromBase64 = function (data, url) {
                    var arr = data.split(','), mime = arr[0].match(/:(.*?);/)[1],
                        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
                    while (n--) {
                        u8arr[n] = bstr.charCodeAt(n);
                    }
                    var filename, suffix;
                    if (typeof url != 'undefined') {
                        var urlArr = url.split('.');
                        filename = url.substr(url.lastIndexOf('/') + 1);
                        suffix = urlArr.pop();
                    } else {
                        filename = Math.random().toString(36).substring(5, 15);
                    }
                    if (!suffix) {
                        suffix = data.substring("data:image/".length, data.indexOf(";base64"));
                    }

                    var exp = new RegExp("\\." + suffix + "$", "i");
                    filename = exp.test(filename) ? filename : filename + "." + suffix;
                    var file = new File([u8arr], filename, {type: mime});
                    return file;
                };

                $(Config.nkeditor.classname || '.editor', form).each(function () {
                    var that = this;
                    var options = $(this).data("nkeditor-options");
                    var editor = Nkeditor.create(that, $.extend({}, {
                        width: '100%',
                        filterMode: false,
                        wellFormatMode: false,
                        allowMediaUpload: true, //是否允许媒体上传
                        allowFileManager: true,
                        allowImageUpload: true,
                        baiduMapKey: Config.nkeditor.baidumapkey || '',
                        baiduMapCenter: Config.nkeditor.baidumapcenter || '',
                        fontSizeTable: ['9px', '10px', '12px', '14px', '16px', '18px', '21px', '24px', '32px'],
                        formulaPreviewUrl: typeof Config.nkeditor != 'undefined' && Config.nkeditor.formulapreviewurl ? Config.nkeditor.formulapreviewurl : "", //数学公式的预览地址
                        cssPath: Config.site.cdnurl + '/assets/addons/nkeditor/plugins/code/prism.css',
                        cssData: "body {font-size: 13px}",
                        fillDescAfterUploadImage: false, //是否在上传后继续添加描述信息
                        themeType: typeof Config.nkeditor != 'undefined' ? Config.nkeditor.theme : 'black', //编辑器皮肤,这个值从后台获取
                        fileManagerJson: Fast.api.fixurl("/addons/nkeditor/index/attachment/module/" + Config.modulename),
                        items: [
                            'source', 'undo', 'redo', 'preview', 'print', 'template', 'code', 'quote', 'cut', 'copy', 'paste',
                            'plainpaste', 'justifyleft', 'justifycenter', 'justifyright',
                            'justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 'subscript',
                            'superscript', 'clearhtml', 'quickformat', 'selectall',
                            'formatblock', 'fontname', 'fontsize', 'forecolor', 'hilitecolor', 'bold',
                            'italic', 'underline', 'strikethrough', 'lineheight', 'removeformat', 'image', 'multiimage', 'graft',
                            'media', 'insertfile', 'table', 'hr', 'emoticons', 'baidumap', 'pagebreak',
                            'anchor', 'link', 'unlink', 'remoteimage', 'search', 'math', 'about', 'fullscreen'
                        ],
                        afterCreate: function () {
                            var self = this;
                            //Ctrl+回车提交
                            Nkeditor.ctrl(document, 13, function () {
                                self.sync();
                                $(that).closest("form").submit();
                            });
                            Nkeditor.ctrl(self.edit.doc, 13, function () {
                                self.sync();
                                $(that).closest("form").submit();
                            });
                            //粘贴上传
                            $("body", self.edit.doc).bind('paste', function (event) {
                                var originalEvent;
                                originalEvent = event.originalEvent;
                                if (originalEvent.clipboardData && originalEvent.clipboardData.files.length > 0) {
                                    uploadFiles.call(self, originalEvent.clipboardData.files);
                                    return false;
                                }
                            });
                            //拖拽上传
                            $("body", self.edit.doc).bind('drop', function (event) {
                                var originalEvent;
                                originalEvent = event.originalEvent;
                                if (originalEvent.dataTransfer && originalEvent.dataTransfer.files.length > 0) {
                                    uploadFiles.call(self, originalEvent.dataTransfer.files);
                                    return false;
                                }
                            });
                        },
                        afterChange: function () {
                            $(this.srcElement[0]).trigger("change");
                        },
                        //自定义处理
                        beforeUpload: function (callback, file) {
                            var file = file ? file : $("input.ke-upload-file", this.form).prop('files')[0];
                            Upload.api.send(file, function (data) {
                                var data = {code: '000', data: {url: Config.nkeditor.fullmode ? Fast.api.cdnurl(data.url, true) : Fast.api.cdnurl(data.url)}, title: '', width: '', height: '', border: '', align: ''};
                                callback(data);
                            });
                        },
                        //错误处理 handler
                        errorMsgHandler: function (message, type) {
                            try {
                                Fast.api.msg(message);
                                console.log(message, type);
                            } catch (Error) {
                                alert(message);
                            }
                        },
                        uploadFiles: uploadFiles
                    }, options || {}));
                    $(this).data("nkeditor", editor);
                });
            });
        }
    }
});

require.config({
    paths: {
        'qrcode': '../addons/notice/js/qrcode',
        'HackTimer': '../addons/notice/js/HackTimer.min',
    },
    shim: {
    }
});

function ajaxInit() {
    if (Config.modulename == 'admin') {
        if (!(Config.controllername == 'index' && Config.actionname == 'index' && Config.notice.admin_real == 1)) {
            return false;
        }
    } else if (Config.modulename == 'index'){
        if (Config.notice.user_real != 1) {
            return false;
        }
        if (!indexUrlCheck()) {
            return false;
        }
    } else {
        return false;
    }
    console.log('ajax_init');

    require(['HackTimer'], function (HackTimer) {
        var url = '';
        if (Config.modulename == 'admin') {
            url = 'notice/admin/statistical';
            noticePanel.insertHtml();
        }
        if (Config.modulename == 'index') {
            url = '/addons/notice/api/statistical';
        }

        // 获取新消息并提示
        function notice() {
            Fast.api.ajax({
                url: url,
                loading: false
            }, function (data, res) {
                if (data.new) {
                    Toastr.info(data.new.content);
                }
                if (Config.modulename == 'admin') {
                    Backend.api.sidebar({
                        'notice/admin': data.num,
                    });
                    noticePanel.render(data.notice_data, data.wait_data);
                }
                setTimeout(function () {
                    notice();
                }, 5000);
                return false;
            }, function () {
                return false;
            });
        };

        notice();
    });
};

function wsInit() {
    if (Config.modulename == 'admin') {
        if (!(Config.controllername == 'index' && Config.actionname == 'index' && Config.notice.admin_real == 2)) {
            return false;
        }
    } else if (Config.modulename == 'index'){
        if (!indexUrlCheck()) {
            return false;
        }
        if (Config.notice.user_real != 2) {
            return false;
        }
    } else {
        return false;
    }
    console.log('ws_init');

    let NhWs = {
        ws: null,
        timer: null,
        bindurl: '',
        url: '',
        connect: function () {
            var ws = new WebSocket(this.url);
            this.ws = ws;

            ws.onmessage = this.onmessage;
            ws.onclose = this.onclose;
            ws.onerror = this.onerror;
            ws.onopen = this.onopen;
        },
        onmessage: function (e) {
            // json数据转换成js对象
            var data = e.data;
            try {
                JSON.parse(data);
                data = JSON.parse(data) ? JSON.parse(data) : data;
            } catch {
                console.log('ws接收到非对象数据', data);
                return true;
            }
            console.log('ws接收到数据', data, e.data);

            var type = data.type || '';
            var resdata = data.data ? data.data : {};
            switch(type){
                case 'init':
                    $.ajax(NhWs.bindurl, {
                        data: {
                            client_id: data.client_id
                        },
                        method: 'post'
                    })
                    break;
                case "new_notice":
                    if (Config.modulename == 'admin') {
                        Backend.api.sidebar({
                            'notice/admin': resdata.num,
                        });
                    }
                    Toastr.info(resdata.msg);

                    // 发送ajax到后台告诉已经看过这条消息
                    Fast.api.ajax({
                        url: '/addons/notice/api/cache',
                        data: {
                            time: resdata.time,
                            module: Config.modulename
                        },
                        method: 'post'
                    }, function () {
                        return false;
                    });
                    break;
                case "notice_panel":
                    noticePanel.render(resdata.notice_data, resdata.wait_data);
                    break;
            }
        },
        onclose: function () {
            console.log('连接已断开，尝试自动连接');
            setTimeout(function () {
                NhWs.connect();
            }, 5000);
        },

        onopen: function () {
            this.timer = setInterval(function () {
                NhWs.send({"type":"ping"});
            }, 20000);
        },
        onerror: function () {
            console.log('ws连接失败');
            Toastr.error('ws连接失败');
        },

        // 发送数据
        send: function (data) {
            if (typeof data == "object") {
                data = JSON.stringify(data);
            }
            this.ws.send(data);
        },
    };

    if (Config.modulename == 'admin') {
        noticePanel.insertHtml();
        NhWs.bindurl = Fast.api.fixurl('/addons/notice/ws/bindAdmin');
        // ajax请求获取消息数量等
        Fast.api.ajax({
            url: 'notice/admin/statistical',
            loading: false,
            method: 'post',
        }, function (data, res) {
            if (data.new) {
                Toastr.info(data.new.content);
            }
            Backend.api.sidebar({
                'notice/admin': data.num,
            });
            noticePanel.render(data.notice_data, data.wait_data);
            return false;
        }, function () {
            return false;
        });

    }

    if (Config.modulename == 'index') {
        NhWs.bindurl = Fast.api.fixurl('/addons/notice/ws/bind');
        // ajax请求最新获取消息数量等
        Fast.api.ajax({
            url: '/addons/notice/api/statistical',
            loading: false,
            method: 'post',
        }, function (data, res) {
            if (data.new) {
                Toastr.info(data.new.content);
            }
            return false;
        }, function () {
            return false;
        });
    }
    NhWs.url = Config.notice.wsurl;

    require(['HackTimer'], function (HackTimer) {
        NhWs.connect();
    });
};

function indexUrlCheck() {
    if (Config.modulename == 'index') {
        var url = Config.controllername+'/'+Config.actionname;
        if (Config.notice.user_real_url.indexOf('*') === -1) {
            if (Config.notice.user_real_url.indexOf(url) === -1) {
                return false;
            }
        }
    }

    return true;
};

let noticePanel = {
    insertHtml: function () {
        if (!Config.notice.admin_check) {
            return false;
        }

        var html = '   <style>\n' +
            '                    #addon-notice:hover {\n' +
            '                        background: #2A404A;\n' +
            '                    }\n' +
            '\n' +
            '                    #addon-notice:hover>a{\n' +
            '                        color: #ffffff;\n' +
            '                    }\n' +
            '\n' +
            '                    .common-notice-box {\n' +
            '                        padding: 0 !important;\n' +
            '                        width: 320px;\n' +
            '                        border: none !important;\n' +
            '                    }\n' +
            '\n' +
            '                    .common-notice-box li {\n' +
            '                        width: 160px;\n' +
            '                        height: 42px;\n' +
            '                        border: none;\n' +
            '                        border: none !important;\n' +
            '                        text-align: center;\n' +
            '                    }\n' +
            '\n' +
            '                    .common-notice-list {\n' +
            '                        padding: 10px !important;\n' +
            '                    }\n' +
            '\n' +
            '                    .common-notice-list ul {\n' +
            '                        padding: 10px;\n' +
            '                        padding-top: 0px;\n' +
            '                        padding-bottom: 0px;\n' +
            '                    }\n' +
            '\n' +
            '                    .common-notice-list .line {\n' +
            '                        border-bottom: 1px solid #3B525D;\n' +
            '                        margin: 0 -10px;\n' +
            '                    }\n' +
            '\n' +
            '                    .common-notice-list li div{\n' +
            '                        display: inline-block;\n' +
            '                        color: white;\n' +
            '                        line-height: 40px;\n' +
            '                        height: 40px;\n' +
            '                        vertical-align: top;\n' +
            '                    }\n' +
            '\n' +
            '                    .common-notice-list li>a{\n' +
            '                        display: inline-block;\n' +
            '                        width: 100%;\n' +
            '                    }\n' +
            '\n' +
            '                    .common-notice-list li .icon{\n' +
            '                        width: 20px;\n' +
            '                        margin-top: -2px;\n' +
            '                    }\n' +
            '\n' +
            '                    .common-notice-list li .text{\n' +
            '                        width: 160px;\n' +
            '                        overflow:hidden;\n' +
            '                        text-overflow:ellipsis;\n' +
            '                        white-space:nowrap;\n' +
            '                    }\n' +
            '\n' +
            '                    .common-notice-list li .time{\n' +
            '                        width: 80px;\n' +
            '                    }\n' +
            '\n' +
            '                    .common-notice-button {\n' +
            '                        display: flex;\n' +
            '                        flex-direction: row;\n' +
            '                        color: #839DA8;\n' +
            '                        justify-content: space-between;\n' +
            '                        padding-top: 15px;\n' +
            '                        padding-bottom: 0px;\n' +
            '                    }\n' +
            '\n' +
            '                    .common-notice-button a{\n' +
            '                        color: #839DA8;\n' +
            '                    }\n' +
            '\n' +
            '                    .common-notice-box ul li {\n' +
            '                        background: #222D32;\n' +
            '                    }\n' +
            '\n' +
            '                    .common-notice-box ul li.active {\n' +
            '                        background: transparent;\n' +
            '                    }\n' +
            '\n' +
            '                </style>\n' +
            '                <li class="hidden-xs" id="addon-notice"  onmouseleave="$(\'#noticelist\').stop().fadeOut(300);" onmouseenter="$(\'#noticelist\').stop().fadeIn(300);">\n' +
            '                    <a href="#" data-title="消息通知"><i class="fa fa-bell" style="font-size:14px;"></i> 消息\n' +
            '                        <div id="notice-all-num" style="width: 16px;height: 16px;border-radius:50%;background-color: red;color: #FFFFFF;position: absolute; right: 0; top: 10px; line-height: 16px; display: none; text-align: center;"></div>\n' +
            '                    </a>\n' +
            '\n' +
            '                    <div style="position: absolute;width: 320px;opacity: 1;background: #2A404A; overflow: hidden;display:none; left: -160px;" id="noticelist">\n' +
            '                        <div class="panel-heading common-notice-box">\n' +
            '                            <ul class="nav nav-tabs" style="border: none; padding: 0;">\n' +
            '                                <li class="active"><a href="#notice-one" data-toggle="tab" style="color: #FFFFFF; border: none;">待办\n' +
            '                                    <div class="wait-num" style="width: 16px;height: 16px;border-radius:50%;background-color: red;color: #FFFFFF;position: absolute;margin: -21px 44px -43px 86px; line-height: 16px; display: none;">-</div>\n' +
            '                                </a>\n' +
            '\n' +
            '                                </li>\n' +
            '                                <li><a href="#notice-two" data-toggle="tab" style="color: #FFFFFF; border: none;">通知\n' +
            '                                    <div class="notice-num" style="width: 16px;height: 16px;border-radius:50%;background-color: red;color: #FFFFFF;position: absolute;margin: -21px 44px -43px 86px; line-height: 16px; display: none">-</div>\n' +
            '                                </a></li>\n' +
            '                            </ul>\n' +
            '                        </div>\n' +
            '\n' +
            '                        <div id="myTabContent" class="tab-content">\n' +
            '                            <div class="tab-pane fade active in common-notice-list" id="notice-one">\n' +
            '                                <ul>\n' +
            '                                    查询中...\n' +
            '                                </ul>\n' +
            '                            </div>\n' +
            '\n' +
            '                            <div class="tab-pane fade common-notice-list" id="notice-two">\n' +
            '                                <ul>\n' +
            '                                    查询中...\n' +
            '                                </ul>\n' +
            '\n' +
            '                                <div class="line"></div>\n' +
            '                                <div class="common-notice-button">\n' +
            '                                    <a href="javascript:;" class="hidden"  data-url="{:url(\'notice/admin/mark\')}">标记当前已读</a>\n' +
            '                                    <a href="notice/admin" data-title="我的消息" class="btn-addtabs" >查看全部</a>\n' +
            '                                </div>\n' +
            '                            </div>\n' +
            '                        </div>\n' +
            '                    </div>\n' +
            '                </li>';
        $('.user-menu').before(html);
    },

    render: function (noticeData, waitData) {
        // 后台右上角通知/待办等
        // var noticeData = {
        //     num: 5,
        //     list: [
        //         {
        //             'title': '待办01',
        //             'time':'xxx',
        //             'url':'',
        //             'class': '',
        //         },
        //         {
        //             'title': '待办02',
        //             'time':'xxx',
        //             'url':'',
        //         }
        //     ],
        // };
        // noticeData = data.notice_data;

        var noticeHtml = '';
        for (let i = 0; i < noticeData.list.length; i++) {
            var item = noticeData.list[i];
            noticeHtml += '<li>\n' +
                '                    <a class="'+item.class+'" data-title="'+item.atitle+'" href="'+Fast.api.fixurl(item.url)+'">\n' +
                '                        <div class="icon">\n' +
                '                            <img class="logo_img" src="'+Fast.api.cdnurl('/assets/addons/notice/img/icon2.png')+'">\n' +
                '                        </div>\n' +
                '                        <div class="text">'+item.title+'</div>\n' +
                '                        <div class="time">'+item.time+'</div>\n' +
                '                    </a>\n' +
                '                </li>';
        }
        if (!noticeHtml) {
            noticeHtml = '<div class="tip-text text-center" style="color: #ffffff">暂无待办</div>';
        }
        $('#notice-two ul').html(noticeHtml);
        if (noticeData.num > 0) {
            $('.notice-num').show().text(noticeData.num);
        } else {
            $('.notice-num').hide().text(noticeData.num);
        }

        // var waitData = {
        //     num: 0,
        //     list: [
        //         {
        //             'title': '待办aaa',
        //             'time':'xxx',
        //             'url':'server/order',
        //             'class': 'btn-addtabs'
        //         },
        //         {
        //             'title': '待办8988',
        //             'time':'xxx',
        //             'url':'',
        //         }
        //     ],
        // };
        // waitData = data.wait_data;


        var waitHtml = '';
        for (let i = 0; i < waitData.list.length; i++) {
            var item = waitData.list[i];
            waitHtml += '<li>\n' +
                '                    <a class="'+item.class+'" data-title="'+item.atitle+'" href="'+Fast.api.fixurl(item.url)+'">\n' +
                '                        <div class="icon">\n' +
                '                            <img class="logo_img" src="'+Fast.api.cdnurl('/assets/addons/notice/img/icon1.png')+'">\n' +
                '                        </div>\n' +
                '                        <div class="text">'+item.title+'</div>\n' +
                '                        <div class="time">'+item.time+'</div>\n' +
                '                    </a>\n' +
                '                </li>';
        }
        if (!waitHtml) {
            waitHtml = '<div class="tip-text text-center" style="color: #ffffff">暂无待办</div>';
        }
        $('#notice-one ul').html(waitHtml);
        if (waitData.num > 0) {
            $('.wait-num').show().text(waitData.num);
        } else {
            $('.wait-num').hide().text(waitData.num);
        }

        var allNoticeAllNum = waitData.num + noticeData.num;
        if (allNoticeAllNum > 0) {
            $('#notice-all-num').show().text(allNoticeAllNum);
        } else {
            $('#notice-all-num').hide().text(allNoticeAllNum);
        }
    }
};


require([], function (undefined) {
    // ajax轮询
    ajaxInit();

    wsInit();

    // 后台绑定按钮
    if (Config.modulename == 'admin' && Config.controllername == 'general.profile' && Config.actionname == 'index') {
        $('[type="submit"]').before('<button style="margin-right: 5px;" type="button" class="btn btn-primary btn-dialog"  data-url="notice/admin_mptemplate/bind">模版消息(公众号)</button>');
    }

});
});